<?php
namespace app\admin\controller;

use app\admin\model\Storetp as StoretpModel;
use app\admin\model\Store;
use think\Request;
use think\Config;
use think\Cache;
use think\Validate;

class Storetp extends Base
{
	/*
	 *	列表
	*/
	public function index()
	{
		$map = [];
        if (!empty($this->request->param('keywords'))) {
            $map['name'] = $this->request->param('keywords');
        }
        if (!empty($this->request->param('status'))) {
            $map['status'] = $this->request->param('status');
        }

		$list = StoretpModel::order('id DESC')->paginate(10);

			// dd($list);
		$menu = self::getMenuArr();

		return view('index', compact('list', 'menu'));
	}

	/*
	 *	添加
	*/
	public function add()
	{
		if(Request::instance()->isPost()){
			$data = $this->request->param();
			// dd($data);
	        $validate = new Validate([
	            ['name', 'require', '请输入分类名称'],
	            ['pic', 'require', '请上传图片'],
	        ]);
	        if (!$validate->check($data)) {
	            return error($validate->getError());
	        }

	        $res = StoretpModel::create([
	        	'name' => $data['name'],
	        	'pic' => $data['pic'],
	        ]);

	        if(!$res){
	        	return error('添加失败');
	        }
	        logger(2, "新增storetp图片");

	        return success(['url'=>"/admin/storetp/index"], '添加成功');
		} 
		$menu = self::getMenuArr();

		return view('add', compact('menu'));
	}

	/*
	 *	添加分类
	*/
	public function edit()
	{
		$id = $this->request->param('id');
		$detail = StoretpModel::find($id);

		if(Request::instance()->isPost()){
			$data = $this->request->param();
			// dd($data);
	        $validate = new Validate([
	            ['name', 'require', '请输入描述'],
	            ['pic', 'require', '请上传图片'],
	        ]);
	        if (!$validate->check($data)) {
	            return error($validate->getError());
	        }
	        
	        if($detail['pic'] != $data['pic']){
	            @unlink(ROOT_PATH . 'public' . DS . 'uploads' . DS . $detail['pic']);
	        }

	        $res = StoretpModel::where('id', $data['id'])->update($data);

	        if($res || $res == false){
	        	logger(2, "编辑storetp");

	        	return success(['url'=>"/admin/storetp/index"], '更新成功');

	        }

	        return error('更新失败');
		}

		$menu = self::getMenuArr();

		return view('edit', compact('detail', 'menu'));
	}

	/*
	 *	删除分类
	*/
	public function del()
	{
		$id = $this->request->param('id');
		if(empty($id)){
			return error('参数有误');
		}

		$infos = Store::where('type_id', $id)->count();
		if($infos > 0){
			return error('请先删除分类下的图片');
		}

		$detail = StoretpModel::find($id);

        if($detail['pic']){
            @unlink(ROOT_PATH . 'public' . DS . 'uploads' . DS . $detail['pic']);
        }

		if(!$detail){
			return error('记录不存在或已被删除');
		}

		$res = StoretpModel::destroy($id);

		if(!$res){
			return error('删除失败');
		}

		logger(2, "删除collection");

		return success(1, '删除成功');

	}
	
}
